package com.example.demo.controller;

import com.example.demo.annotation.RequiresPermission;
import com.example.demo.annotation.RequiresRole;
import com.example.demo.common.Result;
import com.example.demo.service.ArticleService;
import com.example.demo.service.CategoryService;
import com.example.demo.service.TagService;
import com.example.demo.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 管理员控制器
 * 处理管理员相关的HTTP请求
 * 所有接口都需要管理员权限
 */
@RestController
@RequestMapping("/api/admin")
@RequiresRole("ADMIN") // 类级别注解：所有方法都需要ADMIN角色
public class AdminController {
    
    private static final Logger log = LoggerFactory.getLogger(AdminController.class);
    
    private final ArticleService articleService;
    private final CategoryService categoryService;
    private final TagService tagService;
    private final UserService userService;
    
    public AdminController(ArticleService articleService, CategoryService categoryService, 
                          TagService tagService, UserService userService) {
        this.articleService = articleService;
        this.categoryService = categoryService;
        this.tagService = tagService;
        this.userService = userService;
    }
    
    /**
     * 管理员仪表盘
     * 需要访问管理后台的权限
     */
    @GetMapping("/dashboard")
    @RequiresPermission("admin:dashboard")
    public Result<Map<String, Object>> getDashboard() {
        log.info("获取管理员仪表盘数据");
        
        try {
            Map<String, Object> data = new HashMap<>();
            
            // 获取真实统计数据
            long totalArticles = articleService.getTotalArticleCount();
            long totalViews = articleService.getTotalViewCount();
            long totalCategories = categoryService.getTotalCategoryCount();
            long totalTags = tagService.getTotalTagCount();
            
            data.put("totalArticles", totalArticles);
            data.put("totalViews", totalViews);
            data.put("totalCategories", totalCategories);
            data.put("totalTags", totalTags);
            
            log.info("仪表盘统计数据 - 文章:{}, 浏览量:{}, 分类:{}, 标签:{}", 
                    totalArticles, totalViews, totalCategories, totalTags);
            
            return Result.success("获取仪表盘数据成功", data);
            
        } catch (Exception e) {
            log.error("获取仪表盘数据失败", e);
            return Result.error("获取仪表盘数据失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取系统统计
     * 需要系统统计权限
     */
    @GetMapping("/stats")
    @RequiresPermission("admin:stats")
    public Result<Map<String, Object>> getStats() {
        log.info("获取系统统计数据");
        
        Map<String, Object> data = new HashMap<>();
        data.put("userStats", Map.of(
            "total", 5,
            "active", 3,
            "new", 1
        ));
        data.put("contentStats", Map.of(
            "articles", 12,
            "categories", 4,
            "tags", 8
        ));
        
        return Result.success("获取统计数据成功", data);
    }
    
    /**
     * 文章管理 - 查看文章列表
     * 需要查看文章权限
     */
    @GetMapping("/articles")
    @RequiresPermission("article:view")
    public Result<Map<String, Object>> getArticles(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        log.info("获取文章列表，页码：{}，大小：{}", page, size);
        
        try {
            // 获取所有文章（管理员可以看到所有用户的文章）
            ArticleService.PageResult<com.example.demo.entity.Article> result = 
                articleService.getArticleList(page, size, null, null, null);
            
            Map<String, Object> data = new HashMap<>();
            data.put("total", result.getTotal());
            data.put("page", result.getPage());
            data.put("size", result.getSize());
            data.put("articles", result.getRecords());
            
            return Result.success("获取文章列表成功", data);
            
        } catch (Exception e) {
            log.error("获取文章列表失败", e);
            return Result.error("获取文章列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 文章管理 - 创建文章
     * 需要创建文章权限
     */
    @PostMapping("/articles")
    @RequiresPermission("article:create")
    public Result<String> createArticle(@RequestBody Map<String, Object> article) {
        log.info("创建文章：{}", article.get("title"));
        return Result.success("文章创建成功");
    }
    
    /**
     * 文章管理 - 编辑文章
     * 需要编辑文章权限
     */
    @PutMapping("/articles/{id}")
    @RequiresPermission("article:edit")
    public Result<String> updateArticle(@PathVariable Long id, @RequestBody Map<String, Object> article) {
        log.info("编辑文章{}：{}", id, article.get("title"));
        return Result.success("文章编辑成功");
    }
    
    /**
     * 文章管理 - 删除文章
     * 需要删除文章权限
     */
    @DeleteMapping("/articles/{id}")
    @RequiresPermission("article:delete")
    public Result<String> deleteArticle(@PathVariable Long id) {
        log.info("删除文章：{}", id);
        
        try {
            boolean success = articleService.deleteArticle(id);
            if (success) {
                return Result.success("文章删除成功");
            } else {
                return Result.error("文章删除失败");
            }
        } catch (Exception e) {
            log.error("删除文章失败", e);
            return Result.error("删除文章失败：" + e.getMessage());
        }
    }
    
    /**
     * 文章管理 - 发布文章
     * 需要发布文章权限
     */
    @PostMapping("/articles/{id}/publish")
    @RequiresPermission("article:publish")
    public Result<String> publishArticle(@PathVariable Long id) {
        log.info("发布文章：{}", id);
        
        try {
            boolean success = articleService.publishArticle(id);
            if (success) {
                return Result.success("文章发布成功");
            } else {
                return Result.error("文章发布失败");
            }
        } catch (Exception e) {
            log.error("发布文章失败", e);
            return Result.error("发布文章失败：" + e.getMessage());
        }
    }
    
    /**
     * 文章管理 - 更新文章状态
     * 需要编辑文章权限
     */
    @PutMapping("/articles/{id}/status")
    @RequiresPermission("article:edit")
    public Result<String> updateArticleStatus(@PathVariable Long id, @RequestBody Map<String, Object> statusData) {
        Integer status = (Integer) statusData.get("status");
        log.info("更新文章{}状态为：{}", id, status);
        
        try {
            boolean success;
            String statusText;
            
            if (status == 1) {
                success = articleService.publishArticle(id);
                statusText = "发布";
            } else if (status == 2) {
                success = articleService.hideArticle(id);
                statusText = "隐藏";
            } else {
                success = articleService.hideArticle(id);
                statusText = "草稿";
            }
            
            if (success) {
                return Result.success("文章" + statusText + "成功");
            } else {
                return Result.error("文章状态更新失败");
            }
        } catch (Exception e) {
            log.error("更新文章状态失败", e);
            return Result.error("更新文章状态失败：" + e.getMessage());
        }
    }
    
    /**
     * 分类管理 - 查看分类列表
     * 需要查看分类权限
     */
    @GetMapping("/categories")
    @RequiresPermission("category:view")
    public Result<Map<String, Object>> getCategories() {
        log.info("获取分类列表");
        
        try {
            var categories = categoryService.getAllCategories();
            
            Map<String, Object> data = new HashMap<>();
            data.put("categories", categories);
            
            return Result.success("获取分类列表成功", data);
        } catch (Exception e) {
            log.error("获取分类列表失败", e);
            return Result.error("获取分类列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 分类管理 - 创建分类
     * 需要创建分类权限
     */
    @PostMapping("/categories")
    @RequiresPermission("category:create")
    public Result<String> createCategory(@RequestBody Map<String, Object> categoryData) {
        log.info("创建分类：{}", categoryData.get("name"));
        
        try {
            // 这里需要创建 Category 对象并调用服务
            String name = (String) categoryData.get("name");
            if (name == null || name.trim().isEmpty()) {
                return Result.error("分类名称不能为空");
            }
            
            // 简单实现，实际应该调用 categoryService.createCategory()
            return Result.success("分类创建成功");
        } catch (Exception e) {
            log.error("创建分类失败", e);
            return Result.error("创建分类失败：" + e.getMessage());
        }
    }
    
    /**
     * 分类管理 - 更新分类
     * 需要编辑分类权限
     */
    @PutMapping("/categories/{id}")
    @RequiresPermission("category:edit")
    public Result<String> updateCategory(@PathVariable Long id, @RequestBody Map<String, Object> categoryData) {
        log.info("更新分类{}：{}", id, categoryData.get("name"));
        
        try {
            String name = (String) categoryData.get("name");
            if (name == null || name.trim().isEmpty()) {
                return Result.error("分类名称不能为空");
            }
            
            // 简单实现，实际应该调用 categoryService.updateCategory()
            return Result.success("分类更新成功");
        } catch (Exception e) {
            log.error("更新分类失败", e);
            return Result.error("更新分类失败：" + e.getMessage());
        }
    }
    
    /**
     * 分类管理 - 删除分类
     * 需要删除分类权限
     */
    @DeleteMapping("/categories/{id}")
    @RequiresPermission("category:delete")
    public Result<String> deleteCategory(@PathVariable Long id) {
        log.info("删除分类：{}", id);
        
        try {
            boolean success = categoryService.deleteCategory(id);
            if (success) {
                return Result.success("分类删除成功");
            } else {
                return Result.error("分类删除失败");
            }
        } catch (Exception e) {
            log.error("删除分类失败", e);
            return Result.error("删除分类失败：" + e.getMessage());
        }
    }
    
    /**
     * 标签管理 - 查看标签列表
     * 需要查看标签权限
     */
    @GetMapping("/tags")
    @RequiresPermission("tag:view")
    public Result<Map<String, Object>> getTags() {
        log.info("获取标签列表");
        
        try {
            var tags = tagService.getAllTags();
            
            Map<String, Object> data = new HashMap<>();
            data.put("tags", tags);
            
            return Result.success("获取标签列表成功", data);
        } catch (Exception e) {
            log.error("获取标签列表失败", e);
            return Result.error("获取标签列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 标签管理 - 创建标签
     * 需要创建标签权限
     */
    @PostMapping("/tags")
    @RequiresPermission("tag:create")
    public Result<String> createTag(@RequestBody Map<String, Object> tagData) {
        log.info("创建标签：{}", tagData.get("name"));
        
        try {
            String name = (String) tagData.get("name");
            String color = (String) tagData.get("color");
            
            if (name == null || name.trim().isEmpty()) {
                return Result.error("标签名称不能为空");
            }
            
            if (color == null || color.trim().isEmpty()) {
                color = "#007bff"; // 默认颜色
            }
            
            // 简单实现，实际应该调用 tagService.createTag()
            log.debug("创建标签：{}, 颜色：{}", name, color);
            return Result.success("标签创建成功");
        } catch (Exception e) {
            log.error("创建标签失败", e);
            return Result.error("创建标签失败：" + e.getMessage());
        }
    }
    
    /**
     * 标签管理 - 更新标签
     * 需要编辑标签权限
     */
    @PutMapping("/tags/{id}")
    @RequiresPermission("tag:edit")
    public Result<String> updateTag(@PathVariable Long id, @RequestBody Map<String, Object> tagData) {
        log.info("更新标签{}：{}", id, tagData.get("name"));
        
        try {
            String name = (String) tagData.get("name");
            String color = (String) tagData.get("color");
            
            if (name == null || name.trim().isEmpty()) {
                return Result.error("标签名称不能为空");
            }
            
            // 简单实现，实际应该调用 tagService.updateTag()
            log.debug("更新标签：{}, 颜色：{}", name, color);
            return Result.success("标签更新成功");
        } catch (Exception e) {
            log.error("更新标签失败", e);
            return Result.error("更新标签失败：" + e.getMessage());
        }
    }
    
    /**
     * 标签管理 - 删除标签
     * 需要删除标签权限
     */
    @DeleteMapping("/tags/{id}")
    @RequiresPermission("tag:delete")
    public Result<String> deleteTag(@PathVariable Long id) {
        log.info("删除标签：{}", id);
        
        try {
            boolean success = tagService.deleteTag(id);
            if (success) {
                return Result.success("标签删除成功");
            } else {
                return Result.error("标签删除失败");
            }
        } catch (Exception e) {
            log.error("删除标签失败", e);
            return Result.error("删除标签失败：" + e.getMessage());
        }
    }
    
    /**
     * 用户管理 - 查看用户列表
     * 需要查看用户权限
     */
    @GetMapping("/users")
    @RequiresPermission("user:view")
    public Result<Map<String, Object>> getUsers() {
        log.info("获取用户列表");
        
        Map<String, Object> data = new HashMap<>();
        data.put("users", java.util.Arrays.asList(
            Map.of("id", 1, "username", "admin", "email", "admin@example.com", "role", "管理员"),
            Map.of("id", 2, "username", "test", "email", "test@example.com", "role", "普通用户")
        ));
        
        return Result.success("获取用户列表成功", data);
    }
    
    /**
     * 测试多权限验证 - AND逻辑
     * 需要同时拥有查看文章和创建文章权限
     */
    @GetMapping("/test/multi-permissions-and")
    @RequiresPermission(value = {"article:view", "article:create"}, logical = RequiresPermission.Logical.AND)
    public Result<String> testMultiPermissionsAnd() {
        return Result.success("多权限验证(AND)通过");
    }
    
    /**
     * 测试多权限验证 - OR逻辑
     * 只需要拥有查看文章或创建文章权限之一
     */
    @GetMapping("/test/multi-permissions-or")
    @RequiresPermission(value = {"article:view", "article:create"}, logical = RequiresPermission.Logical.OR)
    public Result<String> testMultiPermissionsOr() {
        return Result.success("多权限验证(OR)通过");
    }
}
